package handle.data;

import save.data.User;
import utils.DataBaseUtil;

import javax.naming.NamingException;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "comment", value = "/comment")
public class comment extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        String comment = request.getParameter("comment").trim();
        int blogId = Integer.parseInt(request.getParameter("blogId"));
        User loginBean = (User) request.getSession(true).getAttribute("loginBean");

        String nowTime = new SimpleDateFormat("YYYY-MM-dd").format(new Date());


        try {
            Connection connection = DataBaseUtil.getConnection();

            String sql = "insert into comment(userId,comment_content,blogId,comment_time) values (?,?,?,?)";

            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setInt(1,loginBean.getUserId());

            preparedStatement.setString(2,comment);

            preparedStatement.setInt(3,blogId);

            preparedStatement.setDate(4, java.sql.Date.valueOf(nowTime));

            preparedStatement.execute();
        } catch (NamingException | SQLException e) {
            System.out.println("e = " + e);;
        }

        request.getRequestDispatcher("detail.jsp").forward(request,response);
    }
}
